/*
 *******************************************************************************
 *
 * Copyright (C) 2019-2020 Dialog Semiconductor.
 * This computer program includes Confidential, Proprietary Information
 * of Dialog Semiconductor. All Rights Reserved.
 *
 *******************************************************************************
 */

package com.example.suota.suota.suota;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;

import androidx.annotation.NonNull;

import com.example.suota.suota.global.SuotaLibConfig;

import java.lang.ref.WeakReference;

class SendChunkOperation extends GattOperation {

    private final WeakReference<SuotaProtocol> suotaProtocolWeakReference;
    private final int chunkCount;
    private final int chunk;
    private final int block;
    private final boolean isLastChunk;
    private long sendStartTime;

    SendChunkOperation(@NonNull SuotaProtocol suotaProtocol,
                       @NonNull BluetoothGattCharacteristic characteristic, byte[] value,
                       int chunkCount, int chunk, int block, boolean isLastChunk) {
        super(characteristic, value);
        suotaProtocolWeakReference = new WeakReference<>(suotaProtocol);
        this.chunkCount = chunkCount;
        this.chunk = chunk;
        this.block = block;
        this.isLastChunk = isLastChunk;
    }

    int getChunkCount() {
        return chunkCount;
    }

    int getChunk() {
        return chunk;
    }

    int getBlock() {
        return block;
    }

    public boolean isLastChunk() {
        return isLastChunk;
    }

    long getSendStartTime() {
        return sendStartTime;
    }

    @Override
    boolean execute(@NonNull BluetoothGatt gatt) {
        if (suotaProtocolWeakReference.get() != null) {
            suotaProtocolWeakReference.get().notifyForSendingChunk(this);
        }
        if (SuotaLibConfig.CALCULATE_STATISTICS)
            sendStartTime = System.currentTimeMillis();
        return executeWriteCharacteristic(gatt);
    }
}
